package com.xiaodeng.xdblogspringboot.interceptors;

import com.xiaodeng.xdblogspringboot.exception.UserException;
import com.xiaodeng.xdblogspringboot.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;

@Component
public class AdminInterceptor extends ServiceInterceptor {
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AdminIntercept {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AdminIntercept adminIntercept = handlerMethod.getMethod().getAnnotation(AdminIntercept.class);
        //如果要访问的方法上没有加这个注解，那么就说明这个方法不需要拦截，否则就需要进行拦截
        if (adminIntercept == null) return true;

        //业务实现
        //令牌验证
        Object adminObj = ThreadLocalUtil.get();
        if (adminObj instanceof Map) {
            @SuppressWarnings("unchecked") // 忽略未检查的转换警告
            Map<String, Object> admin = (Map<String, Object>) adminObj;
            // 检查token是否包含"id","username"声明并且其值是相同类型
            if (admin.containsKey("id") && admin.get("id") instanceof Integer &&
                    admin.containsKey("username") && admin.get("username") instanceof String &&
                admin.get("role")instanceof Integer &&
                admin.containsKey("role")
            ) {
                return true; // 允许管理员访问
            } else {
                // 非管理员权限，返回401状态码
                throw new UserException(401, "非管理员");
            }
        } else {
            // adminObj 不是 Map 类型，处理异常情况
            throw new UserException(400, "无效的管理员信息");
        }

    }

}
